package com.zengqingfa.sharding.jdbc.demo.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;


/**
 *
 * @fileName: DateUtil
 * @author: zengqf3
 * @date: 2021-3-31 8:39
 * @description:
 */
public class DateUtil {

    public static final DateTimeFormatter yearAndMonth = DateTimeFormatter.ofPattern("yyyyMM");

    public static final DateTimeFormatter year = DateTimeFormatter.ofPattern("yyyy");

    public static String getYearAndMonth(Long shardingKey) {
        LocalDateTime localDateTime = getLocalDateTime(shardingKey);
        return yearAndMonth.format(localDateTime);
    }

    public static String getYear(Long shardingKey) {
        LocalDateTime localDateTime = getLocalDateTime(shardingKey);
        return year.format(localDateTime);
    }

    public static String getMonth(Long shardingKey) {
        String yearAndMonth = getYearAndMonth(shardingKey);
        return yearAndMonth.substring(4, 6);
    }

    private static LocalDateTime getLocalDateTime(Long shardingKey) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(shardingKey), ZoneId.systemDefault());
    }

    public static void main(String[] args) {
        //202103
        System.out.println(yearAndMonth.format(LocalDateTime.now()));
        //2021
        System.out.println(year.format(LocalDateTime.now()));
    }
}
